import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTimeStamp } from '@/utils/auth'
import router from '@/router'
const timeOut = 50000
function isTime() {
  const TimeNow = Date.now()
  const setTime = getTimeStamp()
  return TimeNow - setTime > timeOut * 1000
}
// console.log(process.env.VUE_APP_BASE_API)
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})
// request interceptor
request.interceptors.request.use((config) => {
  const token = store.state.user.token
  // console.log(token)
  if (token) {
    if (isTime()) {
      store.dispatch('user/logoutSAction')
      router.push('/login')
      return Promise.reject(new Error('token过期'))
    }
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}
)

// response interceptor
request.interceptors.response.use((response) => {
  const { success, message, data } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(message)
  }
}, err => {
  if (err.response.status === 401) {
    store.dispatch('user/logoutSAction')
    router.push('/login')
    Message.error('token过期')
  } else {
    Message.error(err.message)
    return Promise.reject(err)
  }
})
export default request
